package dao.impl;

import dao.UserDao;
import entity.User;
import org.springframework.jdbc.core.JdbcTemplate;
import resultextractor.UserResultExtractor;
import rowmapper.UserRowMapper;

import java.util.List;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    @Override
    public void insert(User user) {
        String sql=new StringBuffer()
                .append("insert into t_user ")
                .append("    (username,password) ")
                .append("values ")
                .append("    (?,?)")
                .toString();
        jdbcTemplate.update(sql,user.getUsername(),user.getPassword());
    }

    @Override
    public void deleteById(Integer id) {
        String sql=new StringBuffer()
                .append("delete from t_user ")
                .append("where id=? ")
                .toString();
        jdbcTemplate.update(sql,id);
    }

    @Override
    public void update(User user) {
        String sql=new StringBuffer()
                .append("update t_user ")
                .append("set username=?, ")
                .append("    password=? ")
                .append("where id=? ")
                .toString();
        jdbcTemplate.update(sql,user.getUsername()
                               ,user.getPassword()
                               ,user.getId());
    }

    @Override
    public List<User> selectAll() {
        String sql=new StringBuffer()
                .append("select * ")
                .append("from t_user ")
                .toString();
        return jdbcTemplate.query(sql,new UserRowMapper());
    }

    @Override
    public User selectById(Integer id) {
        String sql=new StringBuffer()
                .append("select * ")
                .append("from t_user ")
                .append("where id=? ")
                .toString();
//        List<User> users= (List<User>) jdbcTemplate.queryForObject(sql,new UserRowMapper(),id);
//        return users.size()==0?null:users.get(0);
        return jdbcTemplate.query(sql,new UserResultExtractor(),id);
    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
